/**
 * 同步任务执行模态框
 * 支持用户指定自定义增量值和其他执行参数
 */

import React, { useState, useEffect } from 'react';
import {
  Modal,
  Form,
  Input,
  Switch,
  Space,
  Alert,
  Divider,
  Typography,
  Row,
  Col,
  Tooltip,
  Button
} from 'antd';
import {
  PlayCircleOutlined,
  InfoCircleOutlined,
  ThunderboltOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';
import type { SyncTask, SyncExecutionRequest, SyncType } from '../types/sync';

const { Text, Title } = Typography;

interface SyncTaskExecuteModalProps {
  visible: boolean;
  task: SyncTask | null;
  loading: boolean;
  onExecute: (request: Omit<SyncExecutionRequest, 'task_id'>) => Promise<void>;
  onCancel: () => void;
}

const SyncTaskExecuteModal: React.FC<SyncTaskExecuteModalProps> = ({
  visible,
  task,
  loading,
  onExecute,
  onCancel
}) => {
  const [form] = Form.useForm();
  const [forceFullSync, setForceFullSync] = useState(false);

  // 重置表单
  useEffect(() => {
    if (visible && task) {
      form.resetFields();
      setForceFullSync(false);
      
      // 如果是增量同步，设置默认的增量值提示
      if (task.sync_type === 'incremental') {
        const defaultValue = task.incremental_start_value || task.last_incremental_value;
        if (defaultValue) {
          form.setFieldsValue({
            custom_incremental_value: defaultValue
          });
        }
      }
    }
  }, [visible, task, form]);

  // 处理执行
  const handleExecute = async () => {
    try {
      const values = await form.validateFields();
      
      const request: Omit<SyncExecutionRequest, 'task_id'> = {
        force_full_sync: forceFullSync,
        execution_params: {},
        custom_incremental_value: values.custom_incremental_value || undefined
      };

      await onExecute(request);
      form.resetFields();
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  if (!task) return null;

  const isIncrementalTask = task.sync_type === 'incremental';
  const hasIncrementalField = isIncrementalTask && task.incremental_field;

  return (
    <Modal
      title={
        <Space>
          <PlayCircleOutlined />
          执行同步任务
        </Space>
      }
      open={visible}
      onCancel={onCancel}
      width={600}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button
          key="execute"
          type="primary"
          icon={<ThunderboltOutlined />}
          loading={loading}
          onClick={handleExecute}
        >
          开始执行
        </Button>
      ]}
    >
      <div style={{ marginBottom: 16 }}>
        <Title level={5} style={{ margin: 0 }}>
          {task.display_name}
        </Title>
        <Text type="secondary">{task.description}</Text>
      </div>

      <Alert
        message="执行信息"
        description={
          <div>
            <Row gutter={16}>
              <Col span={12}>
                <Text strong>同步类型：</Text>
                <Text>{task.sync_type === 'full' ? '全量同步' : '增量同步'}</Text>
              </Col>
              <Col span={12}>
                <Text strong>批处理大小：</Text>
                <Text>{task.batch_size}</Text>
              </Col>
            </Row>
            {isIncrementalTask && (
              <Row gutter={16} style={{ marginTop: 8 }}>
                <Col span={12}>
                  <Text strong>增量字段：</Text>
                  <Text>{task.incremental_field}</Text>
                </Col>
                <Col span={12}>
                  <Text strong>最后增量值：</Text>
                  <Text>{task.last_incremental_value || '无'}</Text>
                </Col>
              </Row>
            )}
          </div>
        }
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />

      <Form form={form} layout="vertical">
        {/* 强制全量同步选项 */}
        <Form.Item
          label={
            <Space>
              强制全量同步
              <Tooltip title="开启后将忽略增量设置，执行完整的数据同步">
                <InfoCircleOutlined />
              </Tooltip>
            </Space>
          }
        >
          <Switch
            checked={forceFullSync}
            onChange={setForceFullSync}
            checkedChildren="是"
            unCheckedChildren="否"
          />
          {forceFullSync && (
            <Alert
              message="将执行全量同步，忽略所有增量设置"
              type="warning"
              showIcon
              style={{ marginTop: 8 }}
            />
          )}
        </Form.Item>

        {/* 增量同步选项 */}
        {isIncrementalTask && hasIncrementalField && !forceFullSync && (
          <>
            <Divider />
            <Title level={5}>
              <ClockCircleOutlined /> 增量同步设置
            </Title>
            
            <Form.Item
              name="custom_incremental_value"
              label={
                <Space>
                  自定义增量起始值
                  <Tooltip title="可选，指定本次同步的起始值。如果不设置，系统将按优先级使用：任务起始值 > 最后增量值 > 历史记录">
                    <InfoCircleOutlined />
                  </Tooltip>
                </Space>
              }
            >
              <Input
                placeholder={`请输入${task.incremental_field_type === 'timestamp' ? '时间戳' : 'ID'}值`}
                allowClear
              />
            </Form.Item>

            <Alert
              message="增量值优先级说明"
              description={
                <div>
                  <Text>系统将按以下优先级确定增量起始值：</Text>
                  <ol style={{ marginTop: 8, marginBottom: 0 }}>
                    <li><Text strong>自定义增量值</Text>（本次执行指定）</li>
                    <li><Text strong>任务起始值</Text>（{task.incremental_start_value || '未设置'}）</li>
                    <li><Text strong>最后增量值</Text>（{task.last_incremental_value || '无'}）</li>
                    <li><Text strong>历史执行记录</Text>（系统自动查找）</li>
                  </ol>
                </div>
              }
              type="info"
              showIcon
            />
          </>
        )}
      </Form>
    </Modal>
  );
};

export default SyncTaskExecuteModal;
